<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
  <meta charset="UTF-8">
  <title>部门列表</title>
  <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body>
<div class="container">
  <jsp:include page="/header.jsp" />
  <h2>部门列表</h2>

  <%-- 查询表单 --%>
  <form action="${pageContext.request.contextPath}/DepartmentServlet" method="get" class="search-form">
    <input type="hidden" name="action" value="list"> <%-- 确保 action 总是 list --%>
    部门名称: <input type="text" name="searchName" value="<c:out value='${searchNameVal}'/>">
    <input type="submit" value="查询">
    <a href="${pageContext.request.contextPath}/DepartmentServlet?action=list" class="button-link">显示全部</a>
  </form>

  <p><a href="${pageContext.request.contextPath}/DepartmentServlet?action=new">添加新部门</a></p>
  <table>
    <tr>
      <th>ID</th>
      <th>部门名称</th>
      <th>负责人</th>
      <th>操作</th>
    </tr>
    <c:forEach var="dept" items="${listDepartment}">
      <tr>
        <td>${dept.id}</td>
        <td><c:out value="${dept.name}"/></td>
        <td>
          <c:choose>
            <c:when test="${not empty dept.managerName}">
              <c:out value="${dept.managerName}"/> (ID: ${dept.managerId})
            </c:when>
            <c:otherwise>
              无
            </c:otherwise>
          </c:choose>
        </td>
        <td>
          <a href="${pageContext.request.contextPath}/DepartmentServlet?action=edit&id=${dept.id}">编辑</a> |
          <a href="${pageContext.request.contextPath}/DepartmentServlet?action=delete&id=${dept.id}&searchName=<c:out value='${searchNameVal}'/>"
             onclick="return confirm('确定删除 ${dept.name} 吗？');">删除</a>
        </td>
      </tr>
    </c:forEach>
    <c:if test="${empty listDepartment}">
      <tr><td colspan="4">没有找到相关部门。</td></tr>
    </c:if>
  </table>
</div>
</body>
</html>
